<template>
  <div class="merchant">
    <!-- 搜索框 -->
    <div class="merchant_top">
      <el-input
        v-model="merchant_inp"
        size="large"
        clearable
        :prefix-icon="Search"
        placeholder="请输入要查找的内容"
        @input="(e) => (merchant_inp = e)"
      />
      <el-button
        class="inp_but"
        type="primary"
        :icon="Search"
        circle
        @click="handleckInp"
      />
      <el-input
        v-model="merchant_address_inp"
        size="large"
        clearable
        :prefix-icon="Search"
        placeholder="请输入要查找的地址"
        @input="(e) => (merchant_address_inp = e)"
      />
      <el-button
        class="inp_but"
        type="primary"
        :icon="LocationFilled"
        circle
        @click="handleckAddressInp"
      />
      <el-button
        size="large"
        type="success"
        round
        :icon="Star"
        @click="merchant_add_dialogVisible = true"
        >添加</el-button
      >
    </div>
    <!-- 渲染数据 -->
    <el-table
      :data="merchantList"
      border
      style="width: 100%"
      stripe
      height="3000px"
      table-layout="auto"
    >
      <el-table-column label="商家号" prop="_id" width="120" />
      <el-table-column fixed prop="merchant_dat" label="注册日期" width="200">
        <template v-slot="scope">
          <el-tag>{{ dataFliter(scope.row.merchant_dat) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column type="expand">
        <template v-slot="{ row }">
          <el-card :body-style="{ padding: '0px' }">
            <el-image
              class="image"
              style="width: 260px; height: 260px"
              fit="fill"
              :src="`http://localhost:3000/${row.merchant_img}`"
              :preview-src-list="[`http://localhost:3000/${row.merchant_img}`]"
            />
            <div style="padding: 14px">
              <div class="bottom">
                <time class="time">注册日期:{{ dataFliter(row.merchant_dat) }}</time>
                <el-button text class="button">Operating</el-button>
              </div>
              <el-collapse accordion>
                <el-collapse-item
                  :title="row.merchant_name + '点击了解详情'"
                  name="{{row._id}}"
                >
                  <div>
                    {{ row.merchant_desc }}
                  </div>
                </el-collapse-item>
              </el-collapse>
            </div>
          </el-card>
        </template>
      </el-table-column>
      <el-table-column prop="merchant_name" label="商家名" width="180" />
      <!-- merchant_img -->
      <el-table-column prop="merchant_img" label="商家图片" width="180">
        <template v-slot="{ row }">
          <el-image
            style="width: 110px; height: 110px"
            :src="`http://localhost:3000/${row.merchant_img}`"
            fit="fill"
            :preview-src-list="[`http://localhost:3000/${row.merchant_img}`]"
          />
        </template>
      </el-table-column>

      <el-table-column prop="merchant_rote" label="评分" width="210">
        <template v-slot="scope">
          <el-rate
            v-model="scope.row.merchant_rote"
            allow-half
            show-score
            disabled
            score-template="{value} 分"
          />
        </template>
      </el-table-column>
      <el-table-column prop="merchant_desc:" label="商家简介" width="110">
        <template v-slot="{ row }">
          <div id="wrap_text">
            {{ row.merchant_desc }}
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="merchant_address" label="商家地址"> </el-table-column>

      <el-table-column fixed="right" label="功能操作" width="360">
        <template v-slot="{ row }">
          <el-button
            size="large"
            type="danger"
            round
            :icon="Delete"
            @click="handleckDelUser(row._id)"
            >删除</el-button
          >
          <el-button
            size="large"
            type="primary"
            round
            :icon="Edit"
            @click="
              () => {
                handleckUppUser(row);
              }
            "
            >修改</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 渲染数据结束 -->
    <!-- 添加数据开始 -->
    <el-dialog
      v-model="merchant_add_dialogVisible"
      title="添加商家数据"
      width="30%"
      :before-close="handleClose"
    >
      <!-- 添加表单开始 -->
      <el-form
        :rules="merchant_add_rules"
        ref="merchant_add_formRef"
        :model="merchant_add_ValidateForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="商家名称" prop="merchant_name">
          <el-input
            v-model="merchant_add_ValidateForm.merchant_name"
            placeholder="请输入商家名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="商户图片" prop="merchant_img">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:3000/lsj/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img
              v-if="merchant_img"
              :src="`http://localhost:3000/${merchant_img}`"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="商家地址" prop="merchant_address">
          <el-input
            v-model="merchant_add_ValidateForm.merchant_address"
            placeholder="请输入商家地址"
          ></el-input>
        </el-form-item>

        <el-form-item label="商家简介" prop="merchant_desc">
          <el-input
            show-word-limit
            maxlength="300"
            type="textarea"
            placeholder="请输入你想要输入的内容限制在300字以内"
            v-model="merchant_add_ValidateForm.merchant_desc"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="user_add_submitForm(merchant_add_formRef)"
            >添加</el-button
          >
          <el-button @click="resetForm(merchant_add_formRef)">重置</el-button>
          <el-popconfirm
            title="你确定要退出当前操作码?"
            @confirm="
              () => {
                merchant_add_formRef.resetFields();
                merchant_add_dialogVisible = false;
                merchant_img = '';
              }
            "
          >
            <template #reference>
              <el-button>取消</el-button>
            </template>
          </el-popconfirm>
        </el-form-item>
      </el-form>
      <!-- 添加表单结束 -->
    </el-dialog>
    <!-- 添加数据结束 -->
    <!-- 修改数据开始 -->
    <el-dialog
      v-model="merchant_upp_dialogVisible"
      title="修改商家数据"
      width="30%"
      :before-close="handleClose"
    >
      <!-- 修改表单开始 -->
      <el-form
        :rules="merchant_upp_rules"
        ref="merchant_upp_formRef"
        :model="merchant_upp_ValidateForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="商家名称" prop="merchant_name">
          <el-input
            v-model="merchant_upp_ValidateForm.merchant_name"
            placeholder="请输入商家名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="商户图片" prop="merchant_img">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:3000/lsj/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess2"
          >
            <img
              v-if="merchant_upp_ValidateForm.merchant_img"
              :src="`http://localhost:3000/${merchant_upp_ValidateForm.merchant_img}`"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="商家地址" prop="merchant_address">
          <el-input
            v-model="merchant_upp_ValidateForm.merchant_address"
            placeholder="请输入商家地址"
          ></el-input>
        </el-form-item>

        <el-form-item label="商家简介" prop="merchant_desc">
          <el-input
            show-word-limit
            maxlength="300"
            type="textarea"
            placeholder="请输入你想要输入的内容限制在300字以内"
            v-model="merchant_upp_ValidateForm.merchant_desc"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="merchant_upp_submitForm(merchant_upp_formRef)"
            >修改</el-button
          >
          <el-button @click="resetForm(merchant_upp_formRef)">重置</el-button>
          <el-popconfirm
            title="你确定要退出当前操作码?"
            @confirm="
              () => {
                merchant_upp_formRef.resetFields();
                merchant_upp_dialogVisible = false;
                merchant_img = '';
              }
            "
          >
            <template #reference>
              <el-button>取消</el-button>
            </template>
          </el-popconfirm>
        </el-form-item>
      </el-form>
      <!-- 修改表单结束 -->
    </el-dialog>
    <!-- 修改数据结束 -->
  </div>
</template>

<script setup>
import {
  Delete,
  Edit,
  Star,
  InfoFilled,
  Search,
  LocationFilled,
  Plus,
} from "@element-plus/icons-vue";
import service from "../../service/service";
import dayjs from "dayjs";
import { onMounted, reactive, toRefs } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
let merchantList = ref([]);
import { ref } from "vue";
const merchant_inp = ref("");
const merchant_address_inp = ref("");
const merchant_upp_id = ref("");

const merchant_img = ref("");
const merchant_add_dialogVisible = ref(false);
const merchant_upp_dialogVisible = ref(false);
const merchant_add_formRef = ref();
const merchant_upp_formRef = ref();
// 添加数据表单所用数据
const merchant_add_ValidateForm = reactive({
  merchant_name: "",
  merchant_img: "",
  merchant_address: "",
  merchant_desc: "",
});
// 修改数据表单所用数据
const merchant_upp_ValidateForm = reactive({
  merchant_name: "",
  merchant_img: "",
  merchant_address: "",
  merchant_desc: "",
});

// 添加数据
const user_add_submitForm = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      console.log(merchant_add_ValidateForm, "===merchant_add_ValidateForm");
      service.post("/lsj/addmerchant", merchant_add_ValidateForm).then((res) => {
        console.log(res, "===sss");
        if (res.code == 200) {
          ElMessage({
            message: "又成功入驻了一位商户,名为:" + res.data.name,
            type: "success",
          });
          merchant_add_dialogVisible.value = false;
          merchant_add_formRef.value.resetFields();
          getMerchantList(merchant_inp.value, merchant_address_inp.value);
        }
      });
    } else {
      return false;
    }
  });
};

// 修改数据 展示
let handleckUppUser = (row) => {
  merchant_upp_dialogVisible.value = true;
  merchant_upp_id.value = row._id;
  merchant_upp_ValidateForm.merchant_name = row.merchant_name;
  merchant_upp_ValidateForm.merchant_img = row.merchant_img;
  merchant_upp_ValidateForm.merchant_address = row.merchant_address;
  merchant_upp_ValidateForm.merchant_desc = row.merchant_desc;
};

// 修改数据
const merchant_upp_submitForm = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      service.patch("/lsj/uppmerchant?id=" + merchant_upp_id.value, merchant_upp_ValidateForm).then((res) => {
          console.log(res, "===res");
          if (res.code == 200) {
            ElMessage({
              message: "成功修改了一位用户信息",
              type: "success",
            });
            merchant_upp_dialogVisible.value = false;
            merchant_upp_id.value = "";
            getMerchantList(merchant_inp.value, merchant_address_inp.value);
          }
        });
    } else {
      console.log("error submit!");
      return false;
    }
  });
};

// 删除数据
let handleckDelUser = (id) => {
  service.delete("/lsj/delmerchant", { id: id }).then((res) => {
    if (res.code == 200) {
      ElMessage({
        message: "删除成功",
        type: "success",
      });
      getMerchantList(merchant_inp.value, merchant_address_inp.value);
    }
  });
};

// 上传图片成功回调
let handleAvatarSuccess = (response) => {
  merchant_img.value = response.path;
  merchant_add_ValidateForm.merchant_img = response.path;
};

// 上传图片成功回调
let handleAvatarSuccess2 = (response) => {
  merchant_img.value = response.path;
  merchant_upp_ValidateForm.merchant_img = response.path;
};

// 重置
const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
  merchant_img.value = "";
};

// 确认是否退出
const handleClose = (done) => {
  ElMessageBox.confirm("你确认要退出吗?")
    .then(() => {
      done();
      merchant_img.value = "";
      merchant_add_formRef.value.resetFields();
      merchant_upp_formRef.value.resetFields();
    })
    .catch(() => {
      // catch error
    });
};

// 自定义添加用户验证格式
const merchant_add_rules = reactive({
  merchant_name: [
    { required: true, message: "商家名称不能为空", trigger: "blur" },
    { min: 6, max: 12, message: "姓名最少为 6 最多为 12", trigger: "blur" },
  ],
  merchant_img: [{ required: true, message: "请选择图片" }],
  merchant_address: [{ required: true, message: "商家地址不能为空", trigger: "blur" }],
  merchant_desc: [{ required: true, message: "商家简介不能为空", trigger: "blur" }],
});


// 自定义修改用户验证格式
const merchant_upp_rules = reactive({
  merchant_name: [
    { required: true, message: "商家名称不能为空", trigger: "blur" },
    { min: 6, max: 12, message: "姓名最少为 6 最多为 12", trigger: "blur" },
  ],
  merchant_img: [{ required: true, message: "请选择图片" }],
  merchant_address: [{ required: true, message: "商家地址不能为空", trigger: "blur" }],
  merchant_desc: [{ required: true, message: "商家简介不能为空", trigger: "blur" }],
});

// 请求头信息
const header = {
  Accept: "application/json;charset=UTF-8",
};

// 获取初始化数据及商家数据
let getMerchantList = (names, address) => {
  service.get("/lsj/getmerchant", { name: names, address }, header).then((res) => {
    merchantList.value = res.data;
    return merchantList;
  });
};

// 日期格式转换
let dataFliter = (val, format = "YYYY年MM月DD日 hh:mm:ss") => {
  return dayjs(val).format(format);
};

// 根据输入内容进行查找
let handleckInp = () => {
  getMerchantList(merchant_inp.value.trim(), merchant_address_inp.value.trim());
};
// 根据输入地址进行查找
let handleckAddressInp = () => {
  getMerchantList(merchant_inp.value.trim(), merchant_address_inp.value.trim());
};

// 初始化函数
onMounted(() => {
  getMerchantList(merchant_inp.value, merchant_address_inp.value);
});
</script>

<style lang="scss" scoped>
#wrap_text {
  width: 110px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.merchant_top {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  width: 600px;
  .inp_but {
    margin-left: 12px;
  }
}
</style>
